在上一篇文章中,我們在伺服器端針對客戶端傳來的封包,去做了後續的處理,使伺服器的角色能根據客戶端玩家的指令去做相對應的動作;那在這篇文章中,要來把伺服器運算的結果傳回給所有客戶端,讓客戶端去做相對應的動作。
我們會須要在伺服器端建立一個ServerSend的腳本來負責寄送封包給客戶端,而在客戶端也要一個ClientHandle的腳本來處理所有收到的伺服器封包,同樣的我們也要在客戶端建立連線後,在Client腳本裡初始化封包。
private void InitializeClientData()
{
packetHandlers = new Dictionary<int, PacketHandler>()
{
{ (int)ServerPackets.welcome, ClientHandle.Welcome },
{ (int)ServerPackets.spawnPlayer, ClientHandle.SpawnPlayer },
{ (int)ServerPackets.playerPosition, ClientHandle.PlayerPosition },
{ (int)ServerPackets.playerRotation, ClientHandle.PlayerRotation },
};
Debug.Log("Initialized packets.");
}
public static void PlayerPosition(Player _player)
{
using (Packet _packet = new Packet((int)ServerPackets.playerPosition))
{
_packet.Write(_player.id);
_packet.Write(_player.position);
SendUDPDataToAll(_packet);
}
}
public static void PlayerRotation(Player _player)
{
using (Packet _packet = new Packet((int)ServerPackets.playerRotation))
{
_packet.Write(_player.id); _packet.Write(_player.rotation);
SendUDPDataToAll(_player.id, _packet);
}
}
public static void PlayerPosition(Packet _packet)
{
int _id = _packet.ReadInt();
Vector3 _position = _packet.ReadVector3();
GameManager.players[_id].transform.position = _position;
}
public static void PlayerRotation(Packet _packet)
{
int _id = _packet.ReadInt(); Quaternion _rotation = _packet.ReadQuaternion();
GameManager.players[_id].transform.rotation = _rotation;
}